<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--contain-->
    <el-card>
      <!--tips-->
      <el-alert title="添加商品信息" type="info" center show-icon></el-alert>
      <el-steps
        :space="200"
        :active="stepActive - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        ref="addGoodsFormRef"
        :model="addGoodsForm"
        :rules="addGoodsFormRules"
        label-width="80px"
        label-position="top"
      >
        <el-tabs
          tab-position="left"
          v-model="stepActive"
          :before-leave="beforeTabLeave"
          @tab-click="tabsClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addGoodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input
                v-model="addGoodsForm.goods_price"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input
                v-model="addGoodsForm.goods_weight"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input
                v-model="addGoodsForm.goods_number"
                type="number"
                min="0"
              ></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="addGoodsCateOptions"
                :props="addGoodsCateProp"
                @change="addGoodsCateChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              v-for="item in cateAttrManyTable"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  border
                  :label="item1"
                  v-for="(item1, i) in item.attr_vals"
                  :key="i"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in cateAttrOnlyTable"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              :action="uploadURL"
              :file-list="uploadImgList"
              list-type="picture"
              :headers="uploadToken"
              :on-success="uploadSuccess"
              :on-remove="uoloadRemove"
              :on-preview="uploadPreview"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <vue-editor v-model="content"></vue-editor>
            <el-button
              type="primary"
              class="addGoodsButton"
              @click="confirmAddGoods"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog
      title="图片预览"
      :visible.sync="uploadPreviewVisible"
      width="50%"
    >
      <img :src="imgURL" :alt="imgAlt" class="imgPreview" />
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 自定义校验
    var checkNumber = (rule, value, callback) => {
      if (value < 0) {
        return callback(new Error('数值不能为负数'))
      } else {
        callback()
      }
    }
    return {
      // 控制菜单与tab页
      stepActive: '0',
      activeSel: '',
      // 添加商品提交表单
      addGoodsForm: {
        goods_name: '',
        goods_cat: [],
        goods_price: '0',
        goods_weight: '0',
        goods_number: '0',
        goods_introduce: '',
        pics: [],
        attrs: []
      },
      // 表单验证
      addGoodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 20, message: '长度在1到20个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { validator: checkNumber, trigger: 'blur' }
        ]
      },
      // 层级选择器数据
      addGoodsCateOptions: [],
      // 层级选择器prop规则
      addGoodsCateProp: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 动态参数列表
      cateAttrManyTable: [],
      // 静态属性列表
      cateAttrOnlyTable: [],
      // 上传图片列表
      uploadImgList: [],
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      uploadToken: {
        Authorization: window.sessionStorage.getItem('token')
      },
      uploadPreviewVisible: false,
      imgURL: '',
      imgAlt: '',
      // 编辑器内容
      content: ''
    }
  },
  created() {
    this.getGoodsCateList()
  },
  computed: {},
  methods: {
    // 商品分类列表
    async getGoodsCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.addGoodsCateOptions = res.data
    },
    addGoodsCateChange(val) {
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请选择三级分类！')
        this.addGoodsForm.goods_cat = []
      }
    },
    // 控制tab切换条件
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    tabsClick(tab) {
      if (tab.index === '1') {
        this.activeSel = 'many'
        this.getCateAttrList(this.activeSel)
      } else if (tab.index === '2') {
        this.activeSel = 'only'
        this.getCateAttrList(this.activeSel)
      }
    },
    // 获取商品参数与属性列表
    async getCateAttrList(selValue) {
      const { data: res } = await this.$http.get(
        `categories/${this.addGoodsForm.goods_cat[2]}/attributes`,
        {
          params: {
            sel: selValue
          }
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品参数列表失败！')
      }
      // 判断商品参数类别
      if (selValue === 'many') {
        res.data.forEach(element => {
          element.attr_vals =
            element.attr_vals.length === 0 ? [] : element.attr_vals.split(',')
        })
        this.cateAttrManyTable = res.data
      } else {
        this.cateAttrOnlyTable = res.data
      }
    },
    // 图片上传
    uploadSuccess(response) {
      const picObj = {
        pic: response.data.tmp_path
      }
      this.addGoodsForm.pics.push(picObj)
    },
    // 预览图片
    uploadPreview(file) {
      this.uploadPreviewVisible = true
      this.imgURL = file.response.data.url
      this.imgAlt = file.name
    },
    // 删除图片
    uoloadRemove(file, fileList) {
      const fliePath = file.response.data.tmp_path
      const removeIndex = this.addGoodsForm.pics.findIndex(x => {
        return x.pic === fliePath
      })
      this.addGoodsForm.pics.splice(removeIndex, 1)
    },
    // 提交商品
    confirmAddGoods() {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必填项！')
        this.addGoodsForm.goods_introduce = this.content
        // 处理动态参数
        this.cateAttrManyTable.forEach(item => {
          const manyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(',')
          }
          this.addGoodsForm.attrs.push(manyObj)
        })
        // 处理静态属性
        this.cateAttrOnlyTable.forEach(item => {
          const onlyObj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(onlyObj)
        })
        // 处理商品栏目分类数据类型
        const newAddGoodsForm = this._.cloneDeep(this.addGoodsForm)
        newAddGoodsForm.goods_cat = newAddGoodsForm.goods_cat.join(',')
        console.log(newAddGoodsForm)
        // 发起请求
        const { data: res } = await this.$http.post('goods', newAddGoodsForm)
        console.log(res)

        if (res.meta.status !== 201) {
          return this.$message.error('商品添加失败！')
        }
        this.$message.success('商品添加成功')
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-checkbox {
  margin: 0 8px 0 0 !important;
}
.imgPreview {
  width: 100%;
}
.addGoodsButton {
  float: right;
  margin: 8px 0;
}
</style>
